"""
cURL 解析模块
解析从Chrome浏览器复制的curl命令，提取域名、路径、headers和请求体
"""
import re
import json
from urllib.parse import urlparse, parse_qs


class CurlParser:
    """解析curl命令"""
    
    def __init__(self, curl_command):
        self.curl_command = curl_command.strip()
        
    def parse(self):
        """
        解析curl命令
        返回: {
            'domain': str,
            'url_path': str,
            'headers': dict,
            'body': dict,
            'method': str,
            'full_url': str
        }
        """
        result = {
            'domain': '',
            'url_path': '',
            'headers': {},
            'body': {},
            'method': 'GET',
            'full_url': ''
        }
        
        # 提取URL
        url_match = re.search(r"curl\s+'([^']+)'|curl\s+\"([^\"]+)\"|curl\s+([^\s]+)", self.curl_command)
        if url_match:
            url = url_match.group(1) or url_match.group(2) or url_match.group(3)
            result['full_url'] = url
            
            # 解析URL
            parsed = urlparse(url)
            result['domain'] = f"{parsed.scheme}://{parsed.netloc}"
            result['url_path'] = parsed.path
            if parsed.query:
                result['url_path'] += f"?{parsed.query}"
        
        # 提取HTTP方法
        method_match = re.search(r"-X\s+([A-Z]+)", self.curl_command)
        if method_match:
            result['method'] = method_match.group(1)
        elif '--data' in self.curl_command or '--data-raw' in self.curl_command or '--data-binary' in self.curl_command:
            result['method'] = 'POST'
        
        # 提取Headers
        header_pattern = r"-H\s+'([^']+)'|-H\s+\"([^\"]+)\""
        headers = re.findall(header_pattern, self.curl_command)
        for h in headers:
            header = h[0] or h[1]
            if ':' in header:
                key, value = header.split(':', 1)
                result['headers'][key.strip()] = value.strip()
        
        # 提取请求体
        # 尝试 --data-raw
        data_match = re.search(r"--data-raw\s+'([^']+)'|--data-raw\s+\"([^\"]+)\"|--data-raw\s+([^\s-]+)", 
                              self.curl_command, re.DOTALL)
        if not data_match:
            # 尝试 --data
            data_match = re.search(r"--data\s+'([^']+)'|--data\s+\"([^\"]+)\"|--data\s+([^\s-]+)", 
                                  self.curl_command, re.DOTALL)
        if not data_match:
            # 尝试 --data-binary
            data_match = re.search(r"--data-binary\s+'([^']+)'|--data-binary\s+\"([^\"]+)\"|--data-binary\s+\$'([^']+)'", 
                                  self.curl_command, re.DOTALL)
        if not data_match:
            # 尝试 -d
            data_match = re.search(r"-d\s+'([^']+)'|-d\s+\"([^\"]+)\"|-d\s+([^\s-]+)", 
                                  self.curl_command, re.DOTALL)
        
        if data_match:
            data_str = data_match.group(1) or data_match.group(2) or data_match.group(3)
            # 尝试解析为JSON
            try:
                result['body'] = json.loads(data_str)
            except:
                # 如果不是JSON，存储为字符串
                result['body'] = {'raw': data_str}
        
        return result


def test_parser():
    """测试解析器"""
    # 测试用例1: 带JSON body的POST请求
    curl1 = """curl 'https://api.example.com/v1/users' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer token123' \
  --data-raw '{"name":"test","age":25}'"""
    
    parser1 = CurlParser(curl1)
    result1 = parser1.parse()
    print("测试1:", json.dumps(result1, indent=2, ensure_ascii=False))
    
    # 测试用例2: GET请求
    curl2 = """curl 'https://api.example.com/v1/users?page=1&size=10' \
  -H 'Authorization: Bearer token123'"""
    
    parser2 = CurlParser(curl2)
    result2 = parser2.parse()
    print("\n测试2:", json.dumps(result2, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    test_parser()

